﻿using MvvmCross.Platform;
using MvvmCross.Plugins.Messenger;
using Sidvall.WorkItemManager.UI.Entities;
using Sidvall.WorkItemManager.UI.Messaging;
using System.Threading.Tasks;

namespace Sidvall.WorkItemManager.UI.ViewModels
{
    public partial class WebExecutionContextViewModel
    {
        #region Public Members

        #region Context

        private string _Context;
        public string Context
        {
            get
            {
                return _Context;
            }
            set
            {
                if (_Context == value)
                    return;
                _Context = value;
                RaisePropertyChanged("Context");
            }
        }

        #endregion

        #region OnActiveEntityChanged

        protected override void OnActiveEntityChanged(Sidvall.Business.BusinessObjectChangeMode changeMode, Sidvall.Business.ChildChangedEventArgs childArgs, System.ComponentModel.PropertyChangedEventArgs propertyArgs)
        {
            this.Context = WebExecutionContext.Serialize(this.ActiveEntity);
        }

        #endregion
        #region OnViewEvent

        protected override async Task OnViewEventAsync(Sidvall.UI.Views.ViewEventArgs args)
        {
            if (this.IsSavable)
                this.IsSavable = false;
            await base.OnViewEventAsync(args);
        }

        #endregion

        #region Init

        public void Init(ContextParameter item)
        {
            this.ContextParameter = item;
        }

        #endregion
        #region InitializeContext

        public virtual void InitializeContext()
        {
            this.ActiveEntity = WebExecutionContext.Deserialize(this.Context);
        }

        #endregion
        #region StartAsync

        protected override Task StartAsync()
        {
            var messenger = Mvx.Resolve<IMvxMessenger>();
            this.ViewModelResources.Add(messenger.Subscribe<WorkItemExecutionContextMessage>(OnWorkItemExecutionContextMessage));

            if (this.ContextParameter != null)
            {
                this.Context = this.ContextParameter.Context;
                InitializeContext();
                this.ContextParameter = null;
            }
            return Task.FromResult(false);
        }

        #endregion

        #endregion
        #region Private Members

        private ContextParameter ContextParameter { get; set; }

        #region OnWorkItemExecutionContextMessage

        private void OnWorkItemExecutionContextMessage(WorkItemExecutionContextMessage item)
        {
            if (this.Context == item.Context)
                return;
            this.Context = item.Context;
            InitializeContext();
        }

        #endregion

        #endregion
    }
}